// order-confirm.js
var iFDU = require('../../utils/iFDU.js');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    config: app.config,
    globalData: app.globalData,

    addressId: 0,
    address: {
      receiver: '',
      phone: '',
      fullAddress: ''
    },

    bodyShapeId: 0,
    bodyShape: {

    },

    fromCart: 'false',
    virtual: 0,
    // 默认不需要
    is_need_figure: false,
    is_need_address: false,
    is_need_redbag: false,
    is_virtual: 1,
    goodsList: [],
    goodsArr: [],

    invoice: {
      invoice_type: 0,
      invoice: -1,
      invoice_title: '',
      invoice_code: '',
    },

    redbagId: 0,
    redbag: '未选优惠',
    redbagAmount: 0,
    totalCount: 0,
    totalPrice: 0,
    channelId: 0,
    subProductIds: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var is_need_figure = 1;
    var is_virtual = 1;
    var goodsList = JSON.parse(wx.getStorageSync('goodsList'));
    console.log("order confirm goods", goodsList);
    var goodsArr = []
    for (let j = 0; j < goodsList.length; j++) {
      var itemArr = []
      if (goodsList[j].marketing_goods_propertie_ids != undefined && goodsList[j].marketing_goods_propertie_ids.length > 0) {
        for (let i = 0; i < goodsList[j].marketing_goods_propertie_ids.length; i++) {
          var item = {
            name: goodsList[j].marketing_properties_names[i],
            propertieNames: goodsList[j].marketing_goods_propertie_names[i],
            id: goodsList[j].marketing_goods_propertie_ids[i]
          }
          itemArr.push(item)
        }
      }
      goodsArr[j] = itemArr
    }
    that.setData({
      goodsArr: goodsArr
    })
    // that.data.goodsArr = goodsArr

    var channelId = options.channelId;
    if (channelId) {
      that.data.channelId = channelId;
    }
    var subProductIds = [];
    for (var index in goodsList) {
      subProductIds.push(goodsList[index]['goods_id']);
      this.data.subProductIds = subProductIds // 赋值给subProductIds
      // if (goodsList[index]['is_need_figure'] == 0) {
      //   is_need_figure = 0;
      //   break;
      // }
    }
    for (var index in goodsList) {
      if (goodsList[index]['is_virtual'] == 0) {
        is_virtual = 0;
        break;
      }
    }
   

    wx.removeStorage({
      key: 'goodsList',
      success: function(res) {},
    })

    app.getUserInfo(function (globalData) {
      that.setData({
        globalData: globalData
      });

      iFDU.api.doGet(
        'order/getNeedData',
        {
          userId: globalData.userId,
          subProductIds: subProductIds.join(',')
        },
        function (data) {
          var is_need_figure = data.is_need_figure;
          var is_need_address = data.is_need_address;
          var is_need_redbag = data.is_need_redbag;
          if (is_need_figure) {
            that.loadDefaultBodyShape();
            that.loadBodyShape();
          }
          if (is_need_address) {
            that.loadDefaultAddress();
            that.loadAddress();
          }

          that.setData({
            fromCart: Boolean(options.fromCart),
            virtual: parseInt(options.virtual),
            goodsList: goodsList,
            is_need_figure: is_need_figure,
            is_need_address: is_need_address,
            is_need_redbag: is_need_redbag,
            is_virtual: is_virtual
          });

          that.caculateTotalPrice();
        }
      )
    });
  },

  onShow: function () {
    this.caculateTotalPrice();
  },

  caculateTotalPrice: function () {
    var that = this;
    var items = that.data.goodsList;
    var totalPrice = 0;
    var totalCount = 0;
    for (var index in items) {
      var item = items[index];
      var count = item['goods_count'];
      // 商品价格
      var price = item['goods_price'];
      totalPrice += price * count;
      totalCount += count;

      // 营销商品价格
      if (item['marketing_goods_properties'] && item['marketing_goods_properties'].length > 0) {
        for (var j in item['marketing_goods_properties']) {
          totalPrice += item['marketing_goods_properties'][j]['price'] * count;
        }
      }
    }

    that.setData({
      totalCount: totalCount,
      totalPrice: totalPrice > that.data.redbagAmount ? totalPrice - that.data.redbagAmount : 0
    });
  },

  loadDefaultAddress() {
    var that = this;
    iFDU.api.doGet(
      'address/getDefaultAddress',
      {
        userId: that.data.globalData.userId
      },
      function (data) {
        if (data.addressView) {
          that.setData({
            addressId: data.addressView.id,
            address: data.addressView
          });
        }
      }
    )
  },

  loadDefaultBodyShape: function () {
    var that = this;
    iFDU.api.doGet(
      'bodyshape/getDefaultBodyShape',
      {
        userId: that.data.globalData.userId
      },
      function (data) {
        if (data.bodyShape) {
          that.setData({
            bodyShapeId: data.bodyShape.id,
            bodyShape: data.bodyShape
          });
        }
      }
    )
  },

  loadAddress: function () {
    var that = this;
    if (that.data.addressId > 0) {
      iFDU.api.doGet(
        'address/getAddressById',
        {
          userId: that.data.globalData.userId,
          id: that.data.addressId
        },
        function (data) {
          that.setData({
            address: data.address
          });
        }
      )
    }

  },

  loadBodyShape: function () {
    var that = this;
    if (that.data.bodyShapeId > 0) {
      iFDU.api.doGet(
        'bodyshape/getBodyShapeById',
        {
          userId: that.data.globalData.userId,
          id: that.data.bodyShapeId
        },
        function (data) {
          that.setData({
            bodyShape: data.bodyShape
          });
        }
      )
    }
  },

  selectRedbag: function () {
    wx.navigateTo({
      url: '../redbag-select/redbag-select?redbagId=' + this.data.redbagId + '&subProductIds=' + this.data.subProductIds.join(','),
    })
  },

  selectBodyData: function () {
    wx.navigateTo({
      url: '../body-data-list/body-data-list?needCb=1',
    })
  },

  showSleeveWord: function (e) {
    var id = e.currentTarget.dataset.id;
    var sleeveWord = e.currentTarget.dataset.word;
    var sleeveWordType = e.currentTarget.dataset.type;
    sleeveWord = sleeveWord ? sleeveWord : '';
    wx.navigateTo({
      url: '../sleeve-word/sleeve-word?goodsId=' + id + '&sleeveWord=' + sleeveWord + '&sleeveWordType=' + sleeveWordType,
    })
  },

  selectAddress: function (e) {
    wx.navigateTo({
      url: '../address-list/address-list?needCb=1',
    })
  },

  goPay: function () {
    var that = this;
    var params = {
      userId: that.data.globalData.userId,
      isFromCart: that.data.fromCart
    };

    if (that.data.is_need_address) {
      if (that.data.addressId > 0) {
        params['addressId'] = that.data.addressId;
      } else {
        iFDU.toast.showToast({
          title: '请选择收货地址',
          mask: false
        })
        return;
      }

      if (that.data.redbagId > 0) {
        params['redbagId'] = that.data.redbagId;
      }
    }

    if (that.data.is_need_figure) {
      if (that.data.bodyShapeId > 0) {
        params['bodyShapeId'] = that.data.bodyShapeId;
      } else {
        iFDU.toast.showToast({
          title: '请选择身型数据',
          mask: false
        })
        return;
      }
    }
    
    params['invoiceType'] = that.data.invoice.invoice_type;
    if (that.data.invoice.invoice_type != 0) {
      params['invoice'] = that.data.invoice.invoice;
      params['invoiceTitle'] = that.data.invoice.invoice_title;
      params['invoiceCode'] = that.data.invoice.invoice_code;
    }

    var orderParamOfProducts = [];
    for (var index in that.data.goodsList) {
      var goods = that.data.goodsList[index];
      var productParam = {
        subProductId: goods['goods_id'],
        count: goods['goods_count']
      };
      if (goods['sleeve_word'] && goods['sleeve_word'] != '') {
        productParam['broiderTypeface'] = (goods['sleeve_word_type'] == 1 ? 'yahei' : 'mistral');
        productParam['broiderContent'] = goods['sleeve_word'];
      }
      if (goods['marketing_goods_propertie_ids'] && goods['marketing_goods_propertie_ids'] != '' && goods['marketing_goods_propertie_ids'] != '-1') {
        var count = goods['goods_count'];
        var subMarketingProductIds = [];
        // for (var i = 0; i < count; i++) {
          subMarketingProductIds.push(goods['marketing_goods_propertie_ids']);
        // }
        productParam['subMarketingProductIds'] = subMarketingProductIds.join(',');
      }
      orderParamOfProducts.push(productParam);
    }
    params['orderParamOfProducts'] = JSON.stringify(orderParamOfProducts);
    params['channelId'] = that.data.channelId;
    iFDU.api.doGet('order/createOrder', params, function (data) {
      wx.redirectTo({
        url: '../goods-pay/goods-pay?orderId=' + data.orderId,
      })
    });
  },

  selectInvoice: function (e) {
    var invoice = this.data.invoice;
    var params = [];
    params.push('invoice_type=' + invoice.invoice_type);
    params.push('invoice=' + invoice.invoice);
    params.push('invoice_title=' + invoice.invoice_title);
    params.push('invoice_code=' + invoice.invoice_code);
    wx.navigateTo({
      url: '../invoice/invoice?' + params.join('&'),
    })
  },

  showGoodsDetail: function (e) {
    wx.navigateTo({
      url: '../goods-item/goods-item?goodsId=' + e.currentTarget.dataset.id,
    })
  },

  onShareAppMessage: function (res) {
    var that = this;
    return {
      title: '爱上衬衫，从「逸见」开始…',
      imageUrl: 'http://s.i-fdu.com/runto/wxa/s/yjshare.jpeg',
      path: 'pages/home/home',
      success: function (res) {
      },
      fail: function (res) {
      }
    }
  }
})